<template>
  <div>
    <el-dialog
      top="5vh"
      width="55%"
      :title="title"
      append-to-body
      v-if="visible"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleEditReset"
    >
      <div class="dialog-content">
        <avue-form ref="editForm" v-model="form" :option="option" @submit="handleAddRules">
          <template slot="code">
            <el-input placeholder="请输入编码" v-model="form.code">
              <!--              <el-button slot="append" size="small" icon="el-icon-refresh-right" @click="updateCode"></el-button>-->
            </el-input>
          </template>
          <template slot="preview">
            <el-input v-model="preview" disabled> </el-input>
          </template>
          <template slot="standerCode">
            <h3>标准代码</h3>
            <div class="seqNoRulesList">
              <el-checkbox-group v-model="selectedCode" @change="checkboxOnClick">
                <div v-for="(item, index) in seqNoRulesList">
                  <el-col :span="6" class="col">
                    <el-checkbox :key="item.key" class="custom-check-box" :label="item.key">{{ item.value }}</el-checkbox>
                  </el-col>
                </div>
              </el-checkbox-group>
            </div>
          </template>
          <template slot="pubulicCode">
            <h3>公用代码</h3>
            <div class="seqNoRulesList">
              <el-checkbox-group v-model="selectedCode" @change="checkboxOnClick">
                <div v-for="(item, index) in publicRuleList">
                  <el-col :span="6" class="col">
                    <el-checkbox :key="item.key" class="custom-check-box" :label="item.key">{{ item.value }}</el-checkbox>
                  </el-col>
                </div>
              </el-checkbox-group>
            </div>
          </template>
          <template slot="otherCode">
            <h3>类型代码</h3>
            <div class="seqNoRulesList">
              <el-checkbox-group v-model="selectedCode" @change="checkboxOnClick">
                <div v-for="(item, index) in otherRuleList">
                  <el-col :span="6" class="col">
                    <el-checkbox :key="item.key" class="custom-check-box" :label="item.key">{{ item.value }}</el-checkbox>
                  </el-col>
                </div>
              </el-checkbox-group>
            </div>
          </template>
          <template slot="customCode">
            <h3>自定义字符</h3>
            <div class="data-source">
              <label>数据源:</label>
              <el-tooltip class="item" effect="dark" :content="form.sqlName" placement="top">
                <el-input placeholder="请选择 数据源" v-model="form.sqlName" disabled>
                  <el-button slot="append" icon="el-icon-search" @click="handleBindDatasource"></el-button>
                </el-input>
              </el-tooltip>
            </div>
            <el-checkbox-group v-model="selectedCode" @change="checkboxOnClick">
              <div v-for="(item, index) in customizedPlaceholder">
                <el-col :span="8">
                  <el-checkbox :key="item.code" class="custom-check-box" :label="item.code">{{ item.label + item.code }}</el-checkbox>
                  <el-button type="text" size="small" icon="el-icon-edit" @click="handleEditSubForm(item, index)" :disabled="selectedCode.includes(item.code)">编辑 </el-button>
                  <el-button type="text" size="small" icon="el-icon-delete" :disabled="selectedCode.includes(item.code)" @click="handleDeleteSubCode(index)">删 除 </el-button>
                </el-col>
              </div>
            </el-checkbox-group>
            <el-button class="add-custom-btn" type="text" @click="addCustomCode" icon="el-icon-circle-plus-outline" size="small">添加字符 </el-button>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleEditSubmit">保存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleEditReset">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      top="5vh"
      width="30%"
      title="添加自定义字符"
      append-to-body
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="subVisible"
      @close="handleSudEditReset"
    >
      <avue-form ref="subForm" v-model="subForm" :option="subOption" @submit="handleSubmitCustom">
        <!--        <template slot="dataSource">-->
        <!--          <el-button type="primary" size="small" @click="handleBindDatasource">绑定数据源</el-button>-->
        <!--        </template>-->
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleSubEditSubmit">保存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleSudEditReset">取消</el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </div>
</template>

<script>
import { getStranderCode, getPublicCode, getOtherCode, getKeyValueMap } from '@/util/global';
import { guid } from '@/util/helpers';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { addOrUpdate, getDetail, getSqlName } from '@/api/admin/sequencedefinition';

export default {
  name: 'addSerialNumber',
  components: {
    CommonModalTemplate
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '编辑'
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.form = {
            startSequenceNo: '00001',
            endSequenceNo: '99999',
            hexType: '10'
          };
          this.selectedCode = [];
          // this.title === '新增' && this.updateCode(); // 新增生成code
        }
      },
      immediate: true
    },
    selectedCode(val) {
      // const column = this.findObject(this.option.column, 'filterChar');
      if (val.length) {
        this.$nextTick(() => {
          const result = val.map((item) => ({ label: item, value: item }));
          column.dicData = result;
        });
        // this.form.filterChar = this.form.filterChar.filter((item) => val.includes(item));
      } else {
        column.dicData = [];
        // this.form.filterChar = [];
      }
    }
  },
  data() {
    const code = this.$route.path === '/product/refactor/sysSerialNumberConfig' ? 'sysSerial' : 'serial';
    return {
      form: {
        startSequenceNo: '00001',
        endSequenceNo: '99999',
        hexType: '10'
      },
      fieldMap: getKeyValueMap(),
      code: '',
      tableOption: {},
      editIndex: -1,
      subForm: {
        isFixedCharacter: true
      },
      subOption: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        span: 24,
        column: [
          {
            label: '字符名称',
            prop: 'label'
          },
          {
            label: '字符代码',
            prop: 'code'
          },
          // {
          //   label: '固定字符',
          //   prop: 'isFixedCharacter',
          //   type: 'switch',
          //   value: true,
          //   dicData: [
          //     {
          //       label: '否',
          //       value: false
          //     },
          //     {
          //       label: '是',
          //       value: true
          //     }
          //   ]
          // },
          {
            label: '默认值',
            prop: 'value'
            // control: (val, form) => {
            //   if (form.isFixedCharacter) {
            //     return {
            //       value: { display: true }
            //     };
            //   } else {
            //     return {
            //       value: { display: false }
            //     };
            //   }
            // }
          }
          // {
          //   label: '数据源',
          //   prop: 'dataSqlName',
          //   type: 'search',
          //   appendClick: () => {
          //     this.handleBindDatasource();
          //   },
          //   // formslot: true,
          //   control: (val, form) => {
          //     if (!form.isFixedCharacter) {
          //       return {
          //         dataSqlName: { display: true }
          //       };
          //     } else {
          //       return {
          //         dataSqlName: { display: false }
          //       };
          //     }
          //   }
          // }
        ]
      },
      seqNoRulesList: getStranderCode(),
      publicRuleList: getPublicCode(),
      otherRuleList: [],
      customizedPlaceholder: [],
      customKey: [],
      // selectCode: {
      //   selectedRuleCodes: [],
      //   customRuleCode: [],
      //   publicRuleCode: [],
      //   otherRuleCode: []
      // },
      selectedCode: [],
      subVisible: false,
      subTitle: '',
      option: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        column: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            span: 8,
            cascader: ['subType'],
            dicUrl: `/api/blade-system/dict/dictionary?code=${code}`,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择大类',
                trigger: 'change'
              }
            ]
          },
          {
            label: '小类',
            prop: 'subType',
            dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            type: 'select',
            span: 8,
            rules: [
              {
                required: true,
                message: '请选择小类',
                trigger: 'change'
              }
            ],
            change: ({ column, value }) => {
              if (value) {
                this.otherRuleList = getOtherCode(value);
              } else {
                this.otherRuleList = [];
              }
            }
          },
          {
            label: '规则名称',
            prop: 'name',
            rules: [
              {
                required: true,
                message: '请输入规则名称',
                trigger: 'blur'
              }
            ],
            span: 8
          },
          {
            label: '序列号ID',
            prop: 'code',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入序列号ID',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '进制类型',
            // prop: 'baseType',
            prop: 'hexType',
            span: 8,
            labelTip: '序列号生成流水的进制，十进制为10进1，十六进制为16进1；如进制类型为十进制，</br> 则进制字符为0123456789',
            type: 'select',
            value: '10',
            rules: [
              {
                required: true,
                message: '请输入进制类型',
                trigger: 'blur'
              }
            ],
            dicData: [
              {
                label: '十进制',
                value: '10'
              },
              {
                label: '十六进制',
                value: '16'
              },
              {
                label: '自定义',
                value: 'custom'
              }
            ],
            control: (val, form) => {
              if (val === 'custom') {
                return {
                  hexString: {
                    disabled: false
                  }
                };
              } else {
                return {
                  hexString: {
                    disabled: true
                  }
                };
              }
            },
            change: (val) => {
              if (val.value === '10') {
                this.form.hexString = '0123456789';
              } else if (val.value === '16') {
                this.form.hexString = '0123456789ABCDEF';
              }
            }
          },
          {
            label: '进制字符',
            prop: 'hexString',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入进制字符',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo',
            span: 8,
            value: '00001',
            rules: [
              {
                required: true,
                message: '请输入起始流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo',
            value: '99999',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入结束流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '清零类型',
            prop: 'regressionType',
            type: 'select',
            value: 'Year',
            dicData: [
              {
                label: '不清零',
                value: ''
              },
              {
                label: '年',
                value: 'Year'
              },
              {
                label: '月',
                value: 'Month'
              },
              {
                label: '周',
                value: 'Week'
              },
              {
                label: '日',
                value: 'Day'
              }
            ],
            span: 8,
            rules: [
              {
                required: true,
                message: '请选择清零类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '前缀字符',
            prop: 'prefix',
            labelTip: '生成流水的前缀',
            span: 8
          },
          {
            label: '后缀字符',
            prop: 'suffix',
            labelTip: '生成流水的后缀',
            span: 8
          },
          {
            label: '分隔符',
            span: 8,
            prop: 'delimiter',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=delimiter_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '增量',
            prop: 'incrementQty',
            type: 'number',
            precision: 0,
            value: 1,
            span: 8
          },
          {
            label: '预生成序列号',
            prop: 'isPregenerated',
            type: 'switch', //开关的类型
            align: 'center',
            value: false
          },
          {
            label: '序列号构成规则',
            prop: 'sequenceNoFormat',
            rules: [{ required: true, message: '请选择序列号构成规则', trigger: 'change' }],
            labelTip:
              '[P]：前缀字符,[YY]：两位年份, [YYYY]：四位年份, [M]：月,<br />[W]：周, [D]：日,[S]：流水号, [N]：自定义字符。<br />[B]：后缀字符 <br />如：[YY][M][S][B]<br />若无流水号则没有[S],例如：[YY][M][B]',
            span: 24
          },
          {
            label: '序列号规则预览',
            prop: 'preview',
            slot: true,
            span: 24
          },
          // {
          //   label: '清零过滤字符',
          //   prop: 'filterChar',
          //   type: 'select',
          //   multiple: true,
          //   hide: true,
          //   width: 200,
          //   dicData: []
          // },
          {
            label: '',
            prop: 'standerCode',
            formslot: true,
            labelWidth: 40,
            span: 24
          },
          {
            label: '',
            prop: 'pubulicCode',
            formslot: true,
            labelWidth: 40,
            span: 24
          },
          {
            label: '',
            prop: 'otherCode',
            formslot: true,
            labelWidth: 40,
            span: 24
          },
          {
            label: '',
            prop: 'customCode',
            labelWidth: 40,
            formslot: true,
            span: 24
          }
        ]
      }
    };
  },
  computed: {
    preview() {
      let str = '';
      this.selectedCode.forEach((item) => {
        if (this.customKey.includes(item)) {
          str += this.customizedPlaceholder.find((el) => el.code === item).value || '';
        } else if (this.form.prefix && item === '[P]') {
          // 前缀 和后缀 字符 有值时取其值  无值去默认值
          str += this.form.prefix;
        } else if (this.form.suffix && item === '[B]') {
          str += this.form.suffix;
        } else {
          str += this.fieldMap[item] || '';
        }
      });
      return str;
    }
  },
  methods: {
    async getRowData(id) {
      try {
        const res = await getDetail(id);
        const data = res.data.data;
        if (data.placeholderDataId) {
          const sqlRes = await getSqlName(data.placeholderDataId);
          const sqlData = sqlRes.data.data || {};
          data.sqlName = sqlData.querySql;
        }
        this.formatField(data);
      } catch (e) {
        console.warn(e);
      }
    },
    handleEditReset() {
      this.customizedPlaceholder = [];
      this.$refs.editForm.resetForm();
      this.$emit('update:visible', false);
      this.$emit('closeDialog');
    },
    handleSudEditReset() {
      this.$refs.subForm.resetForm();
      this.subVisible = false;
    },
    handleSubEditSubmit() {
      this.$refs.subForm.submit();
    },
    handleSubmitCustom(form, done) {
      if (this.editIndex === -1) {
        const regex = /^\[[^\]]+\]$/;
        if (regex.test(form.code)) {
          this.customizedPlaceholder.push(form);
        } else {
          this.$message.warning("请输入'[xx]'格式的字符代码'");
          done();
          return;
        }
      } else {
        this.customizedPlaceholder.splice(this.editIndex, 1, form);
      }
      this.customKey = this.customizedPlaceholder.map((item) => item.code);
      done();
      this.subVisible = false;
      this.$refs.subForm.resetForm();
    },

    handleAddRules(form, done) {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          const customizedPlaceholder = this.customizedPlaceholder.filter((item) => this.selectedCode.includes(item.code));
          if (customizedPlaceholder.length) {
            this.form.customizedPlaceholder = JSON.stringify(customizedPlaceholder);
          } else {
            this.form.customizedPlaceholder = '';
          }
          // this.form.filterChar = form.filterChar.join(',');
          if (!this.validatesSequenceNo(this.form.startSequenceNo, this.form.endSequenceNo)) {
            done();
            return;
          }
          if (this.form.type === 'material' && !this.selectedCode.includes('[S]')) {
            this.$message.error('未选择流水[S]');
            done();
            return;
          }
          try {
            const res = await addOrUpdate(this.form);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.customizedPlaceholder = [];
            this.$refs.editForm.resetForm();
            this.$emit('update:visible', false);
            this.$emit('closeDialog');
          } catch (e) {
            console.warn(e);
          }
          done();
        }
      });
    },
    handleEditSubmit(form, done) {
      this.$refs.editForm.submit();
    },
    validatesSequenceNo(startNo, endNo) {
      if (startNo.length !== endNo.length) {
        this.$message.error('起始流水号与结束流水号位数不一致');
      }
      return startNo.length === endNo.length;
    },
    addCustomCode() {
      this.editIndex = -1;
      this.subVisible = true;
      this.subTitle = '添加自定义字符';

      // let len = this.customRuleList.length;
      // this.customRuleList.push({
      //   code: '',
      //   key: `[N${len + 1}]`,
      //   value: `自定义字符${len + 1}`
      // });
    },
    handleBindDatasource() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择数据源（双击进行选择）',
        url: '/api/mes-admin/datasql/page?type=SEQUENCE_DEFINITION',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '数据名称',
            prop: 'name',
            search: true
          },
          {
            label: '数据描述',
            prop: 'remark',
            rules: [
              {
                required: true,
                message: '请输入数据描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否可用',
            search: true,
            prop: 'status',
            type: 'select',
            dataType: 'number',
            dicData: [
              {
                label: '否',
                value: 2
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '主SQL',
            prop: 'querySql',
            type: 'textarea'
          }
        ]
      };
    },
    handleDeleteSubCode(index) {
      this.customizedPlaceholder.splice(index, 1);
    },
    handleEditSubForm(item, index) {
      this.subVisible = true;
      this.subForm = item;
      this.subTitle = '编辑自定义字符';
      this.editIndex = index;
    },
    getSelectedRows(rowData) {
      this.$set(this.form, 'sqlName', rowData.querySql || '');
      this.$set(this.form, 'placeholderDataId', rowData.id || '');
    },
    checkboxOnClick(val) {
      this.form.sequenceNoFormat = this.selectedCode.join('');
    },
    formatField(data) {
      const form = data;
      let reg = /^[0-9]\d*$/g;
      let str = /^[A-F0-9]+$/;
      // 回显进制
      if (!form.hexType) {
        // 兼容问题历史数据  之前没有这个字段 现在有了. 对于之前数据走这个逻辑
        if (reg.test(form.hexString)) {
          form.hexType = '10';
        } else if (str.test(form.hexString)) {
          form.hexType = '16';
        } else {
          form.hexType = 'custom';
        }
      }

      if (form.sequenceNoFormat) {
        // 回显checkBox
        const regex = /\[[^\]]+\]/g;
        const matches = form.sequenceNoFormat.match(regex);
        this.selectedCode = matches;
      }

      // 回显自定义

      if (form.customizedPlaceholder) {
        this.customizedPlaceholder = JSON.parse(form.customizedPlaceholder);
        this.customKey = this.customizedPlaceholder.map((item) => item.code);
      }

      // if (form.filterChar) {
      //   form.filterChar = form.filterChar.split(',') || [];
      // }

      this.form = form;
      console.log(this.form);
    }
    /**
     * 更新编码
     */
    // updateCode() {
    //   this.form.code = guid().substr(24, 12);
    // }
  }
};
</script>

<style scoped lang="scss">
h3 {
  margin: 0;
  line-height: 30px;
}
.add-custom-btn {
  font-size: 14px;
}
.dialog-content {
  height: 70vh;
  overflow-y: scroll;
}
.col {
  line-height: 30px;
  .custom-check-box {
    display: flex;
    align-items: center;
    line-height: 30px;
  }
}
.data-source {
  display: flex;
  margin: 12px 0;
  label {
    width: 60px;
  }
}
</style>
